package cn.wzr.controller;

import static cn.wzr.util.CommonTools.isPositiveInt;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import cn.wzr.dao.impl.CommodityDao;
import cn.wzr.entity.Commodity;
import cn.wzr.global.Const;
import cn.wzr.util.CommonTools;
import cn.wzr.util.upload.UploadValidImage;

@MultipartConfig
@WebServlet(Const.WEBURL_SEPARATOR + Const.ACT_CMDTS_EXPORT)
public class CmdtsExport extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        
       
    }


    /**
     * 通过上传的商品及图片信息产生一个商品对象
     * @param cmdtsTxtArray	所有的商品信息字符串数组
     * @param uploadValidImage	一个商品的图片信息
     * @return 在商品信息中遍历找到对应于图片的商品,生成一个商品对象返回
     */
	private Commodity makeOneCmdtByUpload(String[] cmdtsTxtArray, UploadValidImage uploadValidImage) {
		Commodity commodity;
		for(int i = 0; i<cmdtsTxtArray.length; ++i){
			commodity = new Commodity(cmdtsTxtArray[i]);
			if(commodity.getCmdtSN().equals(uploadValidImage.getCmdtSN())){
				commodity.setImagePath(uploadValidImage.getLongImageNames());
				return commodity;
			}
		}
		
		return null;
	}


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String contextPath = getServletContext().getRealPath(String.valueOf(Const.WEBURL_SEPARATOR));
        CommodityDao commodityDao = CommonTools.getCommodityDao(contextPath);
        List<Commodity> cmdtList = commodityDao.findAll();
        Commodity cmdt = cmdtList.get(0);
        String[] imgPaths = cmdt.getImagePath().split(";");
        String imgPath = contextPath + imgPaths[0];
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("1.xlsx", "UTF-8"));
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/octet-stream");
        		
        OutputStream ops = null;
//        FileInputStream fis =null;
        byte[] buffer = new byte[8192];
        int bytesRead = 0;
        		
        File imgFile = null;
        BufferedImage bufferImg = null;   
       //先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray  
       try {
//           ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); 
           imgFile = new File(imgPath);
           if(!imgFile.exists()){
        	   PrintWriter pw = response.getWriter();
        	   pw.write("图片不存在");
        	   pw.flush();
        	   pw.close();
           }
      
		   InputStream is = new FileInputStream(imgFile);   
		   Workbook wb = new XSSFWorkbook();   
		   byte[] bytes = IOUtils.toByteArray(is);
			int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
			is.close();
			
			CreationHelper helper = wb.getCreationHelper();
			
			//create sheet
		Sheet sheet = wb.createSheet("Sheet1");
		
		// Create the drawing patriarch.  This is the top level container for all shapes. 
		Drawing drawing = sheet.createDrawingPatriarch();
		
		//add a picture shape
		ClientAnchor anchor = helper.createClientAnchor();
		//set top-left corner of the picture,
		//subsequent call of Picture#resize() will operate relative to it
		anchor.setCol1(3);
		anchor.setRow1(2);
		Picture pict = drawing.createPicture(anchor, pictureIdx);
		
		//auto-size picture relative to its top-left corner
		pict.resize();
		
		//save workbook
		String file = "66001.xls";
		if(wb instanceof XSSFWorkbook) file += "x";
		//   	    FileOutputStream fileOut = new FileOutputStream(file);
		ops = response.getOutputStream();
		// 写入excel文件   
		wb.write(ops);
		ops.flush();
		System.out.println("----Excle文件已生成------");
       } catch (Exception e) {
           e.printStackTrace();
       }finally{
           if(ops != null){
                try {
                	ops.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }

    }
}
